package com.huanfion.resource.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    public static final String RESOURCE_ID="res1";

    /**
     * 令牌解析方法：
     * 1.DefaultTokenService:如果你的授权服务器和资源服务器在同一个应用程序上，使用DefaultTokenService
     * 2.RemoteTokenService：资源服务器通过HTTP请求来解码令牌，每次都请求授权服务器断点/oauth/check_token
     *                      使用远程令牌解析需注意暴露/oauth/check_token端口；
     *                     public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
     *                          security.tokenKeyAccess("permitAll()");//开启/oauth/token_key 验证端口无权限可以访问
     *                          security.checkTokenAccess("permitAll()");//开启/oauth/check_token验证端口认证无权限可以访问
     *                          security.allowFormAuthenticationForClients();//表单认证，申请令牌
     *                      }
     * 资源服务令牌解析服务
     * @return
     */
    public ResourceServerTokenServices tokenService(){
        //使用原厂服务请求授权服务器校验token，指定校验token的url，client_id，client_secret
        RemoteTokenServices services=new RemoteTokenServices();
        services.setCheckTokenEndpointUrl("http://localhost:9000/oauth/check_token");
        services.setClientId("client");
        services.setClientSecret("secret");
        return services;
    }

    /**
     * 以代码形式配置资源服务器id，配置文件配置不生效
     * @param resources
     * @throws Exception
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID).stateless(true)
        .tokenServices(tokenService());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/**")
                .authenticated()
                .and()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        ;
    }
}
